import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateResultDto } from './dto/create-result.dto';
import { UpdateResultDto } from './dto/update-result.dto';
import { Result } from './entities/result.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository, UpdateResult } from 'typeorm';
import { PaginationService } from 'src/common/service/pagination.service';
import { DelFlag } from 'src/common/enums/del-flag.enum';
import { PaginationResult } from 'src/common/interfaces/pagination-results.interface';
import { ResultQueryDto } from './dto/query-result.dto';
import { Options } from 'src/common/interfaces/options.interface';

@Injectable()
export class ResultService {
  constructor(
    @InjectRepository(Result)
    private resultRepository: Repository<Result>,
    private paginationService: PaginationService,
  ) { }
  async create(createQuestionDto: CreateResultDto): Promise<Result> {
    const result = this.resultRepository.create(createQuestionDto);
    return this.resultRepository.save(result);
  }

  async findAll(questionQueryDto: ResultQueryDto): Promise<PaginationResult<Result>> {
    const {
      keyword,
      limit, page } = questionQueryDto;
    const where: any = {
      del_flag: DelFlag.ACTIVE
    };

    if (keyword) {
      where.keyword = Like(`%${keyword}%`);
    }
    return this.paginationService.paginate(this.resultRepository, { limit, where, page });
  }

  async findOne(id: string): Promise<Result> {
    const result = await this.resultRepository.findOne({ where: { id, del_flag: DelFlag.ACTIVE } });
    if (!result) {
      throw new NotFoundException(`Result with ID ${id} not found`);
    }
    return result;
  }

  async update(id: string, updateQuestionDto: UpdateResultDto): Promise<Result> {
    await this.resultRepository.update(id, updateQuestionDto);
    const updatedQuestion = await this.resultRepository.findOne({ where: { id, del_flag: DelFlag.ACTIVE } });
    if (!updatedQuestion) {
      throw new NotFoundException(`Result with ID ${id} not found`);
    }
    return updatedQuestion;
  }

  async remove(id: string): Promise<UpdateResult> {
    return await this.resultRepository.update(id, { del_flag: DelFlag.DELETED });
  }

  async delete(id: string): Promise<void> {
    await this.resultRepository.delete(id);
  }
  // 查询所有
  async findAllResultsOptions(): Promise<Options[]> {
    const results = await this.resultRepository.find();
    return results.map(result => ({ label: result.keyword, value: result.id }));
  }
}
